package cake.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cake.dao.CakeDao;
import cake.dao.CategoryDao;
import cake.dao.impl.CakeDaoImpl;
import cake.dao.impl.CategoryDaoImpl;
import cake.entity.Cake;
import cake.entity.Category;
@WebServlet("/productList.html")
public class ProductListServlet extends HttpServlet{
	
	private CakeDao cakeDao=new CakeDaoImpl();
	private CategoryDao categoryDao=new CategoryDaoImpl();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		int cid =0;
		int pageNum=1;
		int total=0;
		int pageSize=3;
		
		if (req.getParameter("cid")!=null && !req.getParameter("cid").isEmpty()) {
			cid=Integer.valueOf(req.getParameter("cid"));
		}
		if (req.getParameter("pageNum")!=null && !req.getParameter("pageNum").isEmpty()) {
			pageNum=Integer.valueOf(req.getParameter("pageNum"));
		}
		
		List<Category> list=categoryDao.getAllCategory();
		req.setAttribute("categories", list);
		List<Cake> cakes=cakeDao.getCakeByCategoryAndStatus(cid, pageNum, pageSize);
		req.setAttribute("cakes", cakes);
		
		total=cakeDao.totalCakeByCategoryIdAndStatus(cid);
		int totalPage=0;
		totalPage=total%pageSize==0?total/pageSize:total/pageSize+1;
		
		req.setAttribute("totalPage", totalPage);
		req.setAttribute("total", total);
		req.setAttribute("pageNum", pageNum);
		req.setAttribute("cid", cid);
		req.getRequestDispatcher("productList.jsp").forward(req, resp);
	}
}
